package ms.platform.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
/**
 * Object与byte[]间相互转换
 * @author zhanghuibo
 *
 */
public class StreamUtils {
	private final static Logger LOGGER = LoggerFactory.getLogger(StreamUtils.class);

    /**
     * constructor
     */
    private StreamUtils() {
    }


    
    /**
     * 
     * 功能描述:对象转换成自己数组 <br>
     * 〈功能详细描述〉
     * 
     * @param obj obj
     * @return byte
     * @throws IOException io exception
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static byte[] objectToByteArray(Object obj){
    	ByteArrayOutputStream byteStream = null;
    	ObjectOutputStream os = null;
    	try{
	        if (obj == null) {
	            return null;
	        }
	        byteStream = new ByteArrayOutputStream();
	        os = new ObjectOutputStream(new BufferedOutputStream(byteStream));
	        os.flush();
	        os.writeObject(obj);
	        os.flush();
	        byte[] sendBuf = byteStream.toByteArray();
	        return sendBuf;
    	}catch(Exception e){
    		LOGGER.error("未知异常["+JSON.toJSONString(obj)+"]",e);
    		return null;
    	}finally{
    		try {
    			if(null !=os){
    				os.close();
    			}
    			if(null != byteStream){
    				byteStream.close();
    			}
			} catch (IOException e) {
				LOGGER.error("流关闭发生异常", e);
			}
    	}
    }

    /**
     * 
     * 功能描述:自己数组转换成对象 <br>
     *
     * @param bytes bytes
     * @return object
     * @throws IOException ioexception
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static Object byteArrayToObject(byte[] bytes) throws IOException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        Object obj = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(new BufferedInputStream(bis));
            obj = ois.readObject();
        } catch (Exception e) {
        	LOGGER.error("StreamUtil日志：", e);
        }finally{
        	try {
				ois.close();
			} catch (Exception e) {
				LOGGER.error("流关闭发生异常", e);
			}
        	try {
				bis.close();
			} catch (Exception e) {
				LOGGER.error("流关闭发生异常", e);
			}
        }
        return obj;
    }
}
